package cn.base.project.exception.handler;

import cn.base.project.exception.custom.BaseException;
import cn.base.project.exception.model.BaseError;
import cn.base.project.utils.http.BaseHttpUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Linwq on 2017/12/21.
 */
@ControllerAdvice
public class BaseExceptionHandler {

    private final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(Exception.class)
    public Object nException(HttpServletRequest request , HttpServletResponse response, Exception e) throws IOException {
        ModelAndView mav = new ModelAndView();
        BaseError be = new BaseError();
        if(BaseHttpUtils.ifJson(request)){
            be.setMessage(e.getMessage());
            mav = (ModelAndView) BaseHttpUtils.noViewRTJson(response , e);
        }else {
            be.setMessage(e.getMessage());
            mav.setViewName(DEFAULT_ERROR_VIEW);
            mav.addObject("url",request.getRequestURL());
            mav.addObject("baseError",be);
        }
        return mav;
    }
    @ExceptionHandler(BaseException.class)
    public Object nBaseException(HttpServletRequest request , HttpServletResponse response, BaseException e) throws IOException {
        ModelAndView mav = new ModelAndView();
        BaseError be = new BaseError(e);
        if(BaseHttpUtils.ifJson(request)){
            mav = (ModelAndView) BaseHttpUtils.noViewRTJson(response , be);
        }else {
            mav.setViewName(DEFAULT_ERROR_VIEW);
            mav.addObject("url",request.getRequestURL());
            mav.addObject("baseError",be);
        }
        return mav;
    }
}
